package cn.broadmax.boot.shiro;

import cn.broadmax.boot.api.ISystemBaseApi;
import cn.broadmax.boot.base.model.LoginUser;
import cn.broadmax.boot.exception.TokenExpireException;
import cn.broadmax.boot.util.JwtUtils;
import cn.broadmax.boot.util.ThreadLocalContext;
import jexx.util.BooleanUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * 登录认证和授权
 * @author jeff
 * @date 2020/6/17
 */
@Slf4j
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private ISystemBaseApi systemBaseApi;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("===============Shiro权限认证开始============");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        Set<String> permissions = new HashSet<>();
        permissions.add("test:test1");
        info.setStringPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken){
        if(authenticationToken.getPrincipal() == null){
            throw new AuthenticationException("认证信息为空!");
        }
        String token = authenticationToken.getPrincipal().toString();

        LoginUser jwtUser;
        try {
            jwtUser = JwtUtils.parseToken(token);
            if(jwtUser == null){
                throw new AuthenticationException("token非法!");
            }
        }
        catch (TokenExpireException e){
            throw new AuthenticationException("token过期,请重新登陆!");
        }
        catch (Exception e){
            throw new AuthenticationException("token非法!");
        }

        LoginUser loginUser = systemBaseApi.getAppUserByUserId(jwtUser.getId());
        if (loginUser == null) {
            throw new AuthenticationException("用户不存在!");
        }
        if(BooleanUtil.isTrue(loginUser.getLocked())){
            throw new AuthenticationException("用户已冻结!");
        }
        ThreadLocalContext.bind(loginUser);
        return new SimpleAuthenticationInfo(loginUser, token, getName());
    }
}
